package org.jeecg.modules.demo.crm.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.crm.entity.CSubProject;
import org.jeecg.modules.demo.crm.entity.CTask;
import org.jeecg.modules.demo.crm.mapper.CSubProjectMapper;
import org.jeecg.modules.demo.crm.service.ICCommonService;
import org.jeecg.modules.demo.crm.service.ICTaskService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 任务功能
 * @Author: jeecg-boot
 * @Date:   2025-06-16
 * @Version: V1.0
 */
@Api(tags="任务功能")
@RestController
@RequestMapping("/crm/cTask")
@Slf4j
public class CTaskController extends JeecgController<CTask, ICTaskService> {
	@Autowired
	private ICTaskService cTaskService;
	 @Autowired
	 private ICCommonService cCommonService;
	 @Autowired
	 private CSubProjectMapper cSubProjectMapper;
	/**
	 * 分页列表查询
	 *
	 * @param cTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务功能-分页列表查询")
	@ApiOperation(value="任务功能-分页列表查询", notes="任务功能-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CTask>> queryPageList(CTask cTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Boolean permissionCheck = cCommonService.taskpermissionCheck();//华瑭特殊
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
		customeRuleMap.put("project_id", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("name", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("projectNo", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("remark", QueryRuleEnum.LIKE_WITH_OR);

		if(cTask.getProcessingStatus() != null && "全部".equals(cTask.getProcessingStatus())) {
			cTask.setProcessingStatus(null);
		}
		if(permissionCheck){
			if("-1".equals(cTask.getProjectId())){
				cTask.setProjectId(null);
			}
			if("-1".equals(cTask.getSubProjectId())){
				cTask.setSubProjectId(null);
			}
		}
        QueryWrapper<CTask> queryWrapper = QueryGenerator.initQueryWrapper(cTask, req.getParameterMap(),customeRuleMap);
		//queryWrapper = cCommonService.permissionDetectionColumn(queryWrapper,"assigned_to");

		if(permissionCheck){
			//如果不是管理员
			/*
			String subProjectId = cSubProjectMapper.subProjectPermissions(sysUser.getId());
			if(subProjectId == null){
				subProjectId = "-1";
			}
			List<Long> idList = Arrays.stream(subProjectId.split(","))
					.map(String::trim)
					.filter(StringUtils::isNotBlank)
					.map(Long::valueOf)
					.collect(Collectors.toList());
			queryWrapper.in("sub_project_id", idList);*/
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			queryWrapper.eq("assigned_to",sysUser.getId());
		}

		Page<CTask> page = new Page<CTask>(pageNo, pageSize);
		IPage<CTask> pageList = cTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param cTask
	 * @return
	 */
	@AutoLog(value = "任务功能-添加")
	@ApiOperation(value="任务功能-添加", notes="任务功能-添加")
	@RequiresPermissions("crm:c_task:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CTask cTask) {
		cTask.setProcessingStatus("待处理");
		if(StringUtils.isEmpty(cTask.getAssignedTo())){
			//默认是自己
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			cTask.setAssignedTo(sysUser.getId());
		}
		cTaskService.save(cTask);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cTask
	 * @return
	 */
	@AutoLog(value = "任务功能-编辑")
	@ApiOperation(value="任务功能-编辑", notes="任务功能-编辑")
	@RequiresPermissions("crm:c_task:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CTask cTask) {
		if(StringUtils.isEmpty(cTask.getAssignedTo())){
			//默认是自己
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			cTask.setAssignedTo(sysUser.getId());
		}
		cTaskService.edit(cTask);
		return Result.OK("操作成功!");
	}


	 @RequestMapping(value = "/processEdit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> processEdit(@RequestBody CTask cTask) {
		 if(StringUtils.isEmpty(cTask.getAssignedTo())){
			 //默认是自己
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 cTask.setAssignedTo(sysUser.getId());
		 }
		 cTaskService.process(cTask);
		 return Result.OK("操作成功!");
	 }

	 @RequestMapping(value = "/acceptanceEdit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> acceptanceEditEdit(@RequestBody CTask cTask) {
		 if(StringUtils.isEmpty(cTask.getAssignedTo())){
			 //默认是自己
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 cTask.setAssignedTo(sysUser.getId());
		 }
		 cTaskService.acceptanceEditEdit(cTask);
		 return Result.OK("操作成功!");
	 }

	 /**
	  *  验收
	  *
	  * @param cTask
	  * @return
	  */
	 @AutoLog(value = "验收")
	 @ApiOperation(value="验收", notes="验收")
	 @RequestMapping(value = "/turnDown", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> turnDown( @RequestBody CTask cTask) {
		 cTaskService.turnDown(cTask);
		 return Result.OK("操作成功!");
	 }



	 /**
	  *  处理
	  *
	  * @param cTask
	  * @return
	  */
	 @AutoLog(value = "处理")
	 @ApiOperation(value="处理", notes="处理")
	 @RequestMapping(value = "/dealWith", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> dealWith( @RequestBody CTask cTask) {
		 cTaskService.dealWith(cTask);
		 return Result.OK("操作成功!");
	 }


	 /**
	  *  处理
	  *
	  * @param cTask
	  * @return
	  */
	 @AutoLog(value = "收录任务单 --直接变成已处理")
	 @ApiOperation(value="收录任务单 --直接变成已处理", notes="收录任务单 --直接变成已处理")
	 @RequestMapping(value = "/included", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> included( @RequestBody CTask cTask) {
		 cTaskService.included(cTask);
		 return Result.OK("操作成功!");
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务功能-通过id删除")
	@ApiOperation(value="任务功能-通过id删除", notes="任务功能-通过id删除")
	@RequiresPermissions("crm:c_task:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cTaskService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务功能-批量删除")
	@ApiOperation(value="任务功能-批量删除", notes="任务功能-批量删除")
	@RequiresPermissions("crm:c_task:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务功能-通过id查询")
	@ApiOperation(value="任务功能-通过id查询", notes="任务功能-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CTask> queryById(@RequestParam(name="id",required=true) String id) {
		CTask cTask = cTaskService.getById(id);
		if(cTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cTask);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cTask
    */
    @RequiresPermissions("crm:c_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CTask cTask) {
        return super.exportXls(request, cTask, CTask.class, "任务功能");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("crm:c_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CTask.class);
    }

	 @ApiOperation(value="任务功能-状态数量", notes="任务功能-状态")
	 @GetMapping(value = "/statusCount")
	 public Result<Map<String,Long>> statusCount(CTask task, HttpServletRequest req) {
		 Map<String,Long> data = cTaskService.statusCount(task,req);
		 return Result.OK(data);
	 }

}
